<template>
    <div class="outbound-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-subtitle">
          {{ isSearching ? `搜索结果（${listingTasks.length}条）` : `待上架任务（${listingTasks.length}条）` }}
        </div>
        <div v-if="isSearching" class="search-status">
          <span class="search-keyword">搜索："{{ searchKeyword }}"</span>
          <button class="clear-search-btn" @click="clearSearch" title="清除搜索">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
      </div>

      <!-- 查询功能区域 -->
      <div class="search-container">
        <div class="search-form">
          <div class="search-row">
            <div class="search-input-wrapper">
              <input type="text" class="search-input" v-model="searchKeyword" placeholder="请输入商品条码搜索" @input="handleSearchInput">
              <button class="search-btn-icon" @click="handleSearch">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="11" cy="11" r="8"></circle>
                  <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                </svg>
              </button>
            </div>
            <button class="refresh-btn" @click="refreshData" title="刷新数据">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M23 4v6h-6"></path>
                <path d="M1 20v-6h6"></path>
                <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"></path>
              </svg>
            </button>
          </div>
        </div>
      </div>

       <!-- 入库计划单卡片列表 - 使用van-list实现上拉加载 -->
       <van-list
        v-model:loading="listLoading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoadMore"
        v-if="listingTasks.length > 0"
      >

        <!-- 出货单卡片列表 -->
        <div class="outbound-list">
        <div class="outbound-card" v-for="(item, index) in listingTasks" :key="index">
          <!-- 出货单整体卡片容器 -->
          <div class="outbound-container-card">
            <!-- 出货单头部信息 -->
            <div class="outbound-header">
              <div class="header-main">
                <div class="outbound-id">{{ item['6864a8654e2949f41199080c'] }}</div>
                <div class="outbound-title">{{ item['689bf4a6ad18b78d3f356d9a'] }}</div>
              
              <div class="outbound-details">
  
                <!-- SKUID -->
                <div class="detail-item">
                  <span class="detail-label">SKUID:  {{ item['689bf4a6ad18b78d3f356d9b']}}</span>
                 </div>
  
                <div class="detail-item">
                  <span class="detail-label">商品条码: {{ item['689bf502ad18b78d3f356dbb'] }}</span>
                </div>
                <div class="quantity-row">
                  <div class="quantity-item">
                    <span class="quantity-label">应上架数</span>
                    <span class="quantity-value">{{ item['687a1cdf8371cd243659c97c']}}</span>
                  </div>
                  <div class="quantity-item">
                    <span class="quantity-label">已上架数</span>
                    <span class="quantity-value">{{item['6870ac7a67415961ee20b136']}}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 领取上架任务按钮 -->
            <div class="task-action-row" >
              <button class="claim-task-btn" @click.stop="claimTask(item)">
                去上架
              </button>
            </div>
  
         
  
          </div>
        </div>
      </div>
    </div>
    
    </van-list>
  
    </div>
  </template>
  
  <script setup>
import { ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { api, config, utils } from 'mdye';
import { showConfirmDialog } from 'vant';

const listLoading = ref(false);
const finished = ref(false);
const pageIndex = ref(0);
const count = ref(0);
const pageSize = 20;

const router = useRouter();
const LISTING_TASK_WORKSHEET_ID = '6864a7614e2949f4119907b9'
const listingTasks = ref([]); // 当前显示的任务列表（可能是搜索结果）
const originalTasks = ref([]); // 原始数据的深拷贝，用于搜索恢复
const searchKeyword = ref(''); // 搜索关键词
const isSearching = ref(false); // 搜索状态


const onLoadMore = () => {
  if (finished.value || listLoading.value) return;

  if (Math.ceil(count.value/pageSize) > pageIndex.value) {
    pageIndex.value++;
    fetchListingTasks(true); // 传入true表示是加载更多
  } else {
    finished.value = true;
  }
};

// 处理搜索输入 - 实时搜索
const handleSearchInput = () => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，恢复原始数据
    listingTasks.value = JSON.parse(JSON.stringify(originalTasks.value));
    isSearching.value = false;
    // 重置分页状态
    resetPagination();
    return;
  }
  
  // 执行搜索
  performSearch();
};

// 处理搜索按钮点击
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，恢复原始数据
    listingTasks.value = JSON.parse(JSON.stringify(originalTasks.value));
    isSearching.value = false;
    // 重置分页状态
    resetPagination();
    return;
  }
  
  // 执行搜索
  performSearch();
};

// 执行搜索逻辑
const performSearch = () => {
  if (!searchKeyword.value.trim()) return;
  
  const keyword = searchKeyword.value.toLowerCase().trim();
  isSearching.value = true;
  
  // 重置分页状态
  resetPagination();
  
  // 从原始数据中搜索，避免重复搜索已过滤的数据
  const filteredTasks = originalTasks.value.filter(item => {
    // 检查商品条码是否包含搜索关键词
    const barcode = item['689bf502ad18b78d3f356dbb'] || '';
    if (barcode.toLowerCase().includes(keyword)) {
      return true;
    }
    
    // 检查SKUID是否包含搜索关键词
    const skuid = item['689bf4a6ad18b78d3f356d9b'] || '';
    if (skuid.toLowerCase().includes(keyword)) {
      return true;
    }
    
    // 检查任务标题是否包含搜索关键词
    const title = item['689bf4a6ad18b78d3f356d9a'] || '';
    if (title.toLowerCase().includes(keyword)) {
      return true;
    }
    
    return false;
  });
  
  // 更新显示的任务列表
  listingTasks.value = filteredTasks;
  console.log(`搜索关键词"${keyword}"，找到${filteredTasks.length}条结果`);
};

// 领取上架任务
const claimTask = (outbound) => {
  showConfirmDialog({
  title: '',
  message:
    '是否领取上架任务？',
})
  .then(() => {
    try {
    const cleanReceipt = JSON.parse(JSON.stringify(outbound));
    console.log('cleanReceipt', cleanReceipt);
    
    router.push({ name: 'listing', state: { receipt: cleanReceipt } });
  } catch (e) {
    console.error('[OutboundOrder] 跳转 Listing 失败:', e);
  }
  })
  .catch(() => {
    return
  });
};

// 刷新数据
const refreshData = () => {
  searchKeyword.value = '';
  isSearching.value = false;
  resetPagination();
  fetchListingTasks();
};

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
  isSearching.value = false;
  // 恢复原始数据
  listingTasks.value = JSON.parse(JSON.stringify(originalTasks.value));
  // 重置分页状态
  resetPagination();
};

// 重置分页状态的函数
const resetPagination = () => {
  pageIndex.value = 0;
  finished.value = false;
  listLoading.value = false;
};

const fetchListingTasks = async (isLoadMore = false) => {
  try {
    listLoading.value = true;
    
    const res = await api.getFilterRows({
      worksheetId: LISTING_TASK_WORKSHEET_ID,
      viewId: config.viewId,
      pageIndex: pageIndex.value + 1, // 明道云API从1开始，所以这里+1
      pageSize: pageSize,
    });

    count.value = res.count;
    console.log('上架任务查询表数据 =>', res);
    console.log('上架任务查询表数据 =>', res.count);
    
    const filteredData = res.data.filter(item => {
      if (JSON.parse(item['6864a8654e2949f411990816'])[0] != '8b097898-0f40-4de8-8803-e30831668fdc') {
        return item;
      }
    });
    
    if (isLoadMore) {
      // 加载更多时，合并数据
      originalTasks.value = [...originalTasks.value, ...filteredData];
      listingTasks.value = JSON.parse(JSON.stringify(originalTasks.value));
    } else {
      // 首次加载或刷新时，替换数据
      originalTasks.value = filteredData;
      listingTasks.value = JSON.parse(JSON.stringify(originalTasks.value));
    }
    
    // 检查是否还有更多数据
    if (pageIndex.value * pageSize >= count.value) {
      finished.value = true;
    }
    
    isSearching.value = false;
    listLoading.value = false;
  } catch (e) {
    console.error('获取上架任务查询表数据失败 =>', e);
    listLoading.value = false;
  }
};


onMounted(() => {
  fetchListingTasks(false); // 首次加载
});
</script>
  
  <style scoped>
  /* 页面背景与入库计划单统一 */
  .outbound-container {
    background: #f8f9fa;
    /* 移除 min-height: 100vh，改为 height: 100% */
    height: 100%;
    padding: 16px;
    color: #000000;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    /* 添加滚动设置但隐藏滚动条 */
    overflow-y: auto;
    overflow-x: hidden;
    /* 隐藏滚动条 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
  }
  
  /* 隐藏 Webkit 浏览器的滚动条 */
  .outbound-container::-webkit-scrollbar {
    display: none;
  }
  
  /* 页面标题样式（与入库计划单一致） */
  .page-header {
    background: #f8b300;
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 20px;
    text-align: center;
    color: #000000;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  .header-icon { font-size: 28px; margin-bottom: 8px; }
  .header-title { font-size: 22px; font-weight: 700; margin-bottom: 6px; }
  .header-subtitle { font-size: 14px; opacity: 0.9; }
  
  /* 搜索状态样式 */
  .search-status {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    margin-top: 8px;
    padding: 8px 16px;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 20px;
    backdrop-filter: blur(10px);
  }
  
  .search-keyword {
    font-size: 13px;
    color: rgba(255, 255, 255, 0.9);
    font-weight: 500;
  }
  
  .clear-search-btn {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
    transition: all 0.2s ease;
    backdrop-filter: blur(10px);
  }
  
  .clear-search-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
  }
  
  .clear-search-btn:active {
    transform: scale(0.95);
  }
  
  .clear-search-btn svg {
    width: 12px;
    height: 12px;
  }
  
  /* 查询功能区域样式 */
  .search-container {
    background: transparent;
    padding: 0;
    margin-bottom: 14px;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-row {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .search-input-wrapper {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
  }
  
  .search-input {
    width: 100%;
    padding: 10px 40px 10px 16px;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    font-size: 14px;
    color: #2d3748;
    background: white;
    transition: all 0.2s ease;
    height: 40px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .search-input:focus {
    outline: none;
    border-color: #f8b300;
    box-shadow: 0 0 0 2px rgba(248, 179, 0, 0.2);
  }
  
  .search-input::placeholder {
    color: #a0aec0;
  }
  
  .search-btn-icon {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: #f8b300;
    border: none;
    border-radius: 50%;
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #000000;
    transition: all 0.2s ease;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }
  
  .search-btn-icon:hover {
    transform: translateY(-50%) scale(1.05);
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.15);
  }
  
  /* 刷新按钮样式 */
  .refresh-btn {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border: none;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: white;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
    flex-shrink: 0;
  }
  
  .refresh-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
  }
  
  .refresh-btn:active {
    transform: scale(0.95);
  }
  
  .refresh-btn svg {
    width: 18px;
    height: 18px;
  }
  
  /* 通用卡片（与入库计划单 plan-card 统一风格） */
  .card,
  .task-card {
    background: white;
    border-radius: 24px;
    padding: 24px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }
  
  .card::before,
  .task-card::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 8px;
    background: #f8b300;
  }
  
  .card:hover,
  .task-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);
  }
  
  .card-content { min-height: 40px; }
  
  .line { font-size: 14px; line-height: 22px; color: #2d3748; }
  .row { display: flex; align-items: center; }
  .spacer { flex: 1; }
  
  /* 调试卡片 */
  .debug-card {
    background: #fff9e6;
    border: 1px dashed #f6ad55;
    color: #8a6d3b;
    border-radius: 12px;
    padding: 12px;
    margin-top: 12px;
  }
  .debug-title { font-weight: 700; margin-bottom: 6px; }
  .debug-line { font-size: 13px; line-height: 20px; }
  .render-btn {
    margin-top: 10px;
    appearance: none;
    background: #fffa;
    border: 1px solid #f6ad55;
    color: #8a6d3b;
    border-radius: 8px;
    padding: 6px 10px;
  }
  
  /* 出货单卡片列表 → 调整为网格，两列（>=768px），单列（移动端），整体更紧凑 */
  .outbound-list {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
    margin-top: 16px;
    padding: 0 4px;
  }
  @media (min-width: 768px) {
    .outbound-list {
      grid-template-columns: repeat(2, 1fr);
    }
  }
  
  .outbound-card {
    display: flex;
    flex-direction: column;
  }
  
  .outbound-container-card {
    background: white;
    border-radius: 16px;
    padding: 12px; /* 由 20px 缩小 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(0, 0, 0, 0.06);
    position: relative;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.2s ease;
  }
  
  .outbound-container-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
  }
  
  .outbound-container-card:active {
    transform: translateY(0);
  }
  
  .outbound-container-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: #f8b300;
  }
  
  /* 出货单头部样式 */
  .outbound-header {
    margin-bottom: 12px; /* 由 20px 缩小 */
  }
  
  .header-main {
    margin-bottom: 10px; /* 由 16px 缩小 */
  }
  
  .outbound-id {
    font-size: 14px; /* 由 18px 缩小 */
    font-weight: 700;
    color: #2d3748;
    margin-bottom: 6px; /* 由 8px 缩小 */
    line-height: 1.3;
  }
  
  .outbound-title {
    font-size: 13px; /* 由 16px 缩小 */
    color: #4a5568;
    line-height: 1.35;
  }
  
  .outbound-details {
    display: flex;
    flex-direction: column;
    gap: 8px; /* 由 12px 缩小 */
  }
  
  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 0; /* 由 8px 缩小 */
  }
  
  .detail-label {
    font-size: 12px; /* 由 14px 缩小 */
    color: #718096;
    font-weight: 500;
  }
  
  .detail-value {
    font-size: 12px; /* 由 14px 缩小 */
    color: #2d3748;
    font-weight: 600;
  }
  
  .quantity-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 6px; /* 由 8px 缩小 */
    padding-top: 10px; /* 由 12px 缩小 */
    border-top: 1px solid #e2e8f0;
  }
  
  .quantity-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    flex: 1;
  }
  
  .quantity-label {
    font-size: 11px; /* 由 12px 缩小 */
    color: #718096;
    margin-bottom: 3px; /* 由 4px 缩小 */
  }
  
  .quantity-value {
    font-size: 14px; /* 由 18px 缩小 */
    font-weight: 700;
    color: #2d3748;
  }
  
  /* 任务操作按钮区域 */
  .task-action-row {
    display: flex;
    justify-content: center;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #e2e8f0;
  }
  
  .claim-task-btn {
    background: #00d4aa;
    color: #ffffff;
    border: none;
    border-radius: 20px;
    padding: 14px 60px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(0, 212, 170, 0.3);
    width: 100%;
    min-height: 52px;
  }
  
  .claim-task-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .claim-task-btn:active {
    transform: translateY(0);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
  
  /* 卡片底部按钮 */
  .card-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-top: 12px;
    padding-top: 10px;
    border-top: 1px solid #e2e8f0;
  }
  .btn {
    flex: 1;
    height: 36px;
    border-radius: 18px;
    border: none;
    font-size: 14px;
    font-weight: 700;
    letter-spacing: 0.5px;
    cursor: pointer;
  }
  .btn.primary {
    background: #f8b300;
    color: #000000;
  }
  .btn.secondary {
    background: #f3f4f6;
    color: #111827;
  }
  .btn:active {
    opacity: 0.9;
  }
  
  /* 任务区域样式 */
  .task-section {
    margin-top: 16px;
  }
  
  .section-title {
    font-size: 14px; /* 由 15px 缩小 */
    font-weight: 600;
    color: #4a5568;
    margin-bottom: 10px; /* 由 12px 缩小 */
    padding-left: 4px;
  }
  
  .task-list {
    display: flex;
    flex-direction: column;
    gap: 10px; /* 由 12px 缩小 */
  }
  
  .task-item {
    display: flex;
    align-items: flex-start;
    gap: 10px; /* 由 12px 缩小 */
    padding: 12px; /* 由 16px 缩小 */
    background: #f8fafc;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
    transition: all 0.2s ease;
  }
  
  .task-item:hover {
    background: #f1f5f9;
    transform: translateY(-1px);
  }
  
  .task-icon {
    font-size: 18px; /* 由 20px 缩小 */
    margin-top: 2px;
  }
  
  .task-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 6px;
  }
  
  .task-title {
    font-size: 14px; /* 由 15px 缩小 */
    font-weight: 600;
    color: #2d3748;
  }
  
  .task-subtitle {
    font-size: 12px; /* 由 13px 缩小 */
    color: #718096;
    line-height: 1.4;
  }
  
  .task-count {
    font-size: 13px; /* 由 14px 缩小 */
    font-weight: 600;
    color: #4a5568;
    margin-top: 4px;
  }
  
  /* 移动端优化（保留） */
  @media (max-width: 768px) {
    .outbound-container-card {
      padding: 12px;
      border-radius: 12px;
    }
    
    .outbound-id {
      font-size: 13px;
    }
    
    .outbound-title {
      font-size: 12px;
    }
    
    .task-item {
      padding: 12px;
    }
    
    .quantity-value {
      font-size: 13px;
    }
  }
  
  /* 移动端查询区域样式优化 */
  .search-container {
    padding: 0 10px;
    margin-bottom: 12px;
    max-width: 100%;
  }
  
  .search-input {
    height: 38px;
    font-size: 13px;
    padding: 8px 36px 8px 14px;
  }
  
  .search-btn-icon {
    width: 24px;
    height: 24px;
    right: 8px;
  }
  
  .search-btn-icon svg {
    width: 14px;
    height: 14px;
  }
  
  /* 移动端搜索状态样式优化 */
  .search-status {
    margin-top: 6px;
    padding: 6px 12px;
    gap: 8px;
  }
  
  .search-keyword {
    font-size: 12px;
  }
  
  .clear-search-btn {
    width: 20px;
    height: 20px;
  }
  
  .clear-search-btn svg {
    width: 10px;
    height: 10px;
  }
  </style> 